package ThreadTest;

/**
 * 创建线程的方式二：实现Runnable接口
 * 1.创建一个实现了Runnable接口的类
 * 2.实现抽象方法
 * 3.创建实现类的对象
 * 4.将此类作为参数放入Thread类的构造器中，创建Thread类的对象
 * 5.调用start
 * 线程同步：
 * 1.同步代码块： synchronized（object）{}   object（同步监视器）是同一个的
 * 2.同步方法：  synchronized
 */
//三个窗口卖票操作
public class MyThread1 implements Runnable {
    private int stats = 100;
    @Override
    public  void run() {
        while (true) {
           show();
        }
    }
    public synchronized void show(){
        if (stats > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ": " + stats);
            stats--;
        }
    }
}

class MyThread1_Test {
    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();

        Thread thread1 = new Thread(myThread1,"窗口一");
        Thread thread2 = new Thread(myThread1);
        Thread thread3= new Thread(myThread1);


        thread2.setName("窗口二：");
        thread3.setName("窗口三：");

        thread1.start();
        thread2.start();
        thread3.start();

    }
}